package io.valuesfeng.picker.adapter;

import android.graphics.Bitmap;
import android.net.Uri;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.BitmapImageViewTarget;
import com.makeramen.roundedimageview.RoundedImageView;

import java.util.List;

import io.valuesfeng.picker.R;


/**
 * Created by dune on 15/12/17.
 */
public class ImageGridViewAdapter extends BaseAdapter {

    private LayoutInflater mInflater;
    private Fragment fragment;
    private List<Uri> data;
    private int maxCount;


    public ImageGridViewAdapter(Fragment fragment, int imageMaxCount, List<Uri> uris) {

        this.maxCount = imageMaxCount;
        this.fragment = fragment;
        this.mInflater = fragment.getActivity().getLayoutInflater();
        data = uris;
    }

    public void setData(List<Uri> list) {
        data = list;
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        if (data.size() < maxCount) {

            return data.size() + 1;
        }
        return data.size();
    }

    public int getImageCount() {

        return data.size();
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        final ViewHolder holder;
        if (convertView != null) {
            holder = (ViewHolder) convertView.getTag();
        } else {
            convertView = mInflater.inflate(R.layout.item_grid_img, parent, false);
            holder = new ViewHolder(convertView);
            convertView.setTag(holder);
        }

        if (position < getCount() - 1 || getImageCount() == maxCount) {


            Glide.with(fragment).load(data.get(position))
                    .asBitmap()
                    .centerCrop()
                    .placeholder(R.drawable.ic_note_img_loading)
                    .thumbnail(0.1f)
                    .into(new BitmapImageViewTarget(holder.ivImageItem) {
                        @Override
                        protected void setResource(Bitmap resource) {
                            holder.ivImageItem.setImageBitmap(resource);
                        }
                    });
        } else {

            Glide.with(fragment).load(R.drawable.ic_add_image_frame_ps)
                    .centerCrop()
                    .into(holder.ivImageItem);
        }


        return convertView;
    }

    static class ViewHolder {

        RoundedImageView ivImageItem;

        ViewHolder(View view) {

            ivImageItem = (RoundedImageView) view.findViewById(R.id.iv_img_item);
        }
    }
}
